package lar.system.network;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

import lar.system.network.msgParser.ParsedMessage;
import android.util.Log;

public class UDPListener extends Listener implements Runnable 
{
	DatagramSocket inSocket;

	public UDPListener(int port)
	{
		try
		{
			inSocket = new DatagramSocket(port);
			//inSocket.setSoTimeout(timeout);								//timeout the receive process every timeout
		}
		catch (IOException e)
		{
			e.printStackTrace();
			Log.d("UDPListener" , "error in initiating socket");
		}
	}

	@Override
	public void run() 
	{
		try 
		{
			int size = 1024;
			byte[] receivedata = new byte[size];
			while(!inSocket.isClosed())
			{
				DatagramPacket recv_packet = new DatagramPacket(receivedata, receivedata.length);
				//  Log.d("UDP", "S: Receiving...");
				inSocket.receive(recv_packet);
				String rec_str = new String(recv_packet.getData());
				rec_str = rec_str.substring(0, recv_packet.getLength());
				InetAddress ipaddress = recv_packet.getAddress();		//where did this packet originate from
				// int port = recv_packet.getPort();
				// String ownIP = myIP();
				ParsedMessage p = new ParsedMessage(rec_str);
				p.Parse();
				p.setAttachment(ipaddress);
				//Log.d("R", "Got broadcast: " + p.getOriginalString());
				this.Q.add(p);

				/*if (rec_str.startsWith(Strings.DISCOVER))
		        {
		        			String ans = Strings.ans_discover(ownIP , android.os.Build.MANUFACTURER +" "+android.os.Build.MODEL);
		        			DatagramPacket ansPacket = new DatagramPacket(ans.getBytes(), ans.length(), ipaddress, port);
		        			inSocket.send(ansPacket);
		        }
		        if (rec_str.startsWith(Strings.ANS_DISCOVER))
		        {
		        			String ip = Strings.getIp(rec_str);
		        			String model = Strings.getModel(rec_str);

		        			Log.d("wifi", "discovered this ip: "+ip+" and this model: "+model+ " whereas my ip is : "+ownIP);
		        			String ipModel = ip + "\n" + model;

		        			if (!ipList.contains(ipModel)) 
		        				{
		        				devices.addElement(ipModel);
		        				ipList.add(ipModel);
		        				}
		        }*/

			}
		} 
		catch (Exception e) 
		{

		}
		//inSocket.close();
	}

	public void shutDown()
	{
		if(inSocket == null) return;
		inSocket.disconnect();
		inSocket.close();
		inSocket = null;
	}

}
